<template>
	<view class="select-ref-container">
		<uni-data-picker :ellipsis="true" :border="false" :placeholder="this.$props.placeholder"
			popup-title="请选择" :localdata="localdata" v-model="inputvalue" @change="onchange"></uni-data-picker>
	</view>
</template>

<script>
	/**
	 * @author liuwqc
	 * @date 2023/09/19
	 * selectRef 下拉参照
	 * @description 下拉参照框
	 * @property {String} docType 档案类型，具体取值见BASEDOC_KEY
	 * @property {String} refType 参照类型
	 * @property {String} valuemode 取值模式
	 */
	export default {
		name: 'select-ref',
		data() {
			return {
				inputvalue: this.processedValue,
				localdata: [],
			};
		},
		props: {
			value: {
				type: [String, Object],
				default: function() {
					return '';
				}
			},
			refType: {
				type: String,
				default: function() {
					return '';
				}
			},
			docType: {
				type: String,
				default: function() {
					return '';
				}
			},
			refData: {
				type: Array,
				default: function() {
					return [];
				}
			},
			textfield: {
				type: String,
				default: function() {
					return 'refname';
				}
			},
			valuefield: {
				type: String,
				default: function() {
					return 'refid';
				}
			},
			valuemode: {
				type: String,
				default: function() {
					return 'single';
				}
			},
			placeholder: {
				type: String,
			}
		},
		watch: {
			/**
			 * @param {Object} newValue 更新后的props
			 * 监听props中的value值变化，并赋值给自身数据属性inputvalue
			 */
			value(newValue) {
				if (typeof newValue === 'object') {
					this.inputvalue = newValue['refid']
				} else {
					this.inputvalue = newValue;
				}
			}
		},
		computed: {
			/**
			 * 处理value值
			 */
			processedValue() {
				if (typeof this.value === 'object') {
					return this.value['refid']
				} else {
					return this.value
				}
			},
			/**
			 * 从缓存中获取localdata的值
			 */
			processedLocaldata() {
				const storageData = uni.getStorageSync(this.$props.docType);
				let localdata = [];
				if (storageData && JSON.stringify(storageData) != '{}') {
					storageData.map((item) => {
						let obj = {
							text: item[this.$props.textfield],
							value: item[this.$props.valuefield]
						};
						localdata.push(obj);
					});
				}
				return localdata;
			}
		},
		methods: {
			onchange(e) {
				this.$emit('input', this.inputvalue);
			},
			getRefValue() {
				let refObj = {};
				this.localdata.map(item => {
					if (item.value == this.inputvalue) {
						refObj['refid'] = item.value;
						refObj['refname'] = item.text;
					}
				})
				return refObj;
			}
		},
		created() {},
		mounted() {
			if (this.$props.refData && this.$props.refData.length != 0) {
				this.localdata = this.$props.refData;
			} else {
				this.localdata = this.processedLocaldata;
			}
			this.inputvalue = this.processedValue;
		}
	};
</script>

<style lang="scss">
	.select-ref-container {
		width: 100%;

		/deep/ .arrow-area {
			display: none;
		}
	}
</style>